﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

namespace YTCMS.Core
{
    public class RequestHelper
    {
        /// <summary>
        /// 判断当前页面是否接收到了Post请求
        /// </summary>
        /// <returns>是否接收到了Post请求</returns>
        public static bool IsPost()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("POST");
        }

        /// <summary>
        /// 判断当前页面是否接收到了Get请求
        /// </summary>
        /// <returns>是否接收到了Get请求</returns>
        public static bool IsGet()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("GET");
        }

        /// <summary>
        /// 返回指定的服务器变量信息
        /// </summary>
        /// <param name="strName">服务器变量名</param>
        /// <returns>服务器变量信息</returns>
        public static string GetServerString(string strName, int maxLen = 4000)
        {
            if (HttpContext.Current.Request.ServerVariables[strName] == null)
                return "";

            return StringHelper.CutString(HttpContext.Current.Request.ServerVariables[strName].ToString().Trim(), 0, maxLen);
        }

        /// <summary>
        /// 返回上一个页面的地址
        /// </summary>
        /// <returns>上一个页面的地址</returns>
        public static string GetUrlReferrer(int maxLen = 4000)
        {
            string retVal = null;

            try
            {
                if (HttpContext.Current.Request.UrlReferrer != null)
                    retVal = HttpContext.Current.Request.UrlReferrer.ToString();
            }
            catch (Exception)
            { }

            if (retVal == null)
                return "";

            return StringHelper.CutString(retVal, 0, maxLen);
        }

        /// <summary>
        /// 得到当前完整主机头
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentFullHost()
        {
            HttpRequest request = System.Web.HttpContext.Current.Request;
            if (!request.Url.IsDefaultPort)
                return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());

            return request.Url.Host;
        }

        /// <summary>
        /// 得到主机头
        /// </summary>
        /// <returns></returns>
        public static string GetHost()
        {
            return HttpContext.Current.Request.Url.Host;
        }


        /// <summary>
        /// 获取当前请求的原始 URL(URL 中域信息之后的部分,包括查询字符串(如果存在))
        /// </summary>
        /// <returns>原始 URL</returns>
        public static string GetRawUrl(int maxLen = 4000)
        {
            return StringHelper.CutString(HttpContext.Current.Request.RawUrl, 0, maxLen);
        }

        /// <summary>
        /// 判断当前访问是否来自浏览器软件
        /// </summary>
        /// <returns>当前访问是否来自浏览器软件</returns>
        public static bool IsBrowserGet()
        {
            string[] BrowserName = { "ie", "opera", "netscape", "mozilla", "konqueror", "firefox" };
            string curBrowser = HttpContext.Current.Request.Browser.Type.ToLower();
            for (int i = 0; i < BrowserName.Length; i++)
            {
                if (curBrowser.IndexOf(BrowserName[i]) >= 0)
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 判断是否来自搜索引擎链接
        /// </summary>
        /// <returns>是否来自搜索引擎链接</returns>
        public static bool IsSearchEnginesGet()
        {
            if (HttpContext.Current.Request.UrlReferrer == null)
                return false;

            string[] SearchEngine = { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom", "yisou", "iask", "soso", "gougou", "zhongsou" };
            string tmpReferrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
            for (int i = 0; i < SearchEngine.Length; i++)
            {
                if (tmpReferrer.IndexOf(SearchEngine[i]) >= 0)
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 获得当前完整Url地址
        /// </summary>
        /// <returns>当前完整Url地址</returns>
        public static string GetUrl(int maxLen = 4000)
        {
            return StringHelper.CutString(HttpContext.Current.Request.Url.ToString(), 0, maxLen);
        }



        /// <summary>
        /// 获得当前页面的名称
        /// </summary>
        /// <returns>当前页面的名称</returns>
        public static string GetPageName()
        {
            string[] urlArr = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
            return urlArr[urlArr.Length - 1].ToLower();
        }

        /// <summary>
        /// 返回表单或Url参数的总个数
        /// </summary>
        /// <returns></returns>
        public static int GetParamCount()
        {
            return HttpContext.Current.Request.Form.Count + HttpContext.Current.Request.QueryString.Count;
        }

        /// <summary>
        /// 获取逗号分隔的数字Id
        /// </summary>
        /// <param name="strName"></param>
        /// <returns></returns>
        public static string GetQueryIds(string strName, int maxLen = 4000)
        {
            string ids = HttpContext.Current.Request.QueryString[strName];

            //Regex regex = new Regex(@"^[\d,]+$");
            //if (string.IsNullOrWhiteSpace(ids) || !regex.IsMatch(ids))
            //{
            //    return string.Empty;
            //} 
            //return ids; 
            return StringHelper.CutString(StringHelper.ReplaceIDS(ids), 0, maxLen);
        }

        /// <summary>
        /// 获取逗号分隔的数字Id
        /// </summary>
        /// <param name="strName"></param>
        /// <returns></returns>
        public static string GetFormIds(string strName, int maxLen = 4000)
        {
            string ids = HttpContext.Current.Request.Form[strName];
            //Regex regex = new Regex(@"^[\d,]+$");
            //if (string.IsNullOrWhiteSpace(ids) || !regex.IsMatch(ids))
            //{
            //    return string.Empty;
            //} 
            //return ids; 
            return StringHelper.CutString(StringHelper.ReplaceIDS(ids), 0, maxLen);
        }

        #region GetString相关

        /// <summary>
        /// 获得指定Url参数的值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <returns>Url参数的值</returns>
        public static string GetQueryString(string strName, int maxLen = 4000)
        {
            return GetQueryString(strName, false, true, maxLen);
        }

        /// <summary>
        /// 获得指定Url参数的值
        /// </summary> 
        /// <param name="strName">Url参数</param>
        /// <param name="sqlSafeCheck">是否进行SQL安全检查</param>
        /// <returns>Url参数的值</returns>
        public static string GetQueryString(string strName, bool sqlSafeCheck, bool isTrim, int maxLen = 4000)
        {
            if (HttpContext.Current.Request.QueryString[strName] == null)
                return "";

            //if (sqlSafeCheck && !StringHelper.IsSafeSqlString(HttpContext.Current.Request.QueryString[strName]))
            //    return "unsafe string";

            //return StringHelper.ReplaceHtml(HttpContext.Current.Request.QueryString[strName].Trim());
            if (sqlSafeCheck)
                return StringHelper.CutString(StringHelper.ReplaceSqlInject(isTrim ? HttpContext.Current.Request.QueryString[strName].Trim() : HttpContext.Current.Request.QueryString[strName]), 0, maxLen);
            else
                return StringHelper.CutString(isTrim ? HttpContext.Current.Request.QueryString[strName].Trim() : HttpContext.Current.Request.QueryString[strName], 0, maxLen);
        }
        /// <summary>
        /// 获得指定表单参数的值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <returns>表单参数的值</returns>
        public static string GetFormString(string strName, int maxLen = 4000)
        {
            return GetFormString(strName, false, true, maxLen);
        }

        /// <summary>
        /// 获得指定表单参数的值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <param name="sqlSafeCheck">是否进行SQL安全检查</param>
        /// <returns>表单参数的值</returns>
        public static string GetFormString(string strName, bool sqlSafeCheck, bool isTrim, int maxLen = 4000)
        {
            if (HttpContext.Current.Request.Form[strName] == null)
                return "";

            //if (sqlSafeCheck && !StringHelper.IsSafeSqlString(HttpContext.Current.Request.Form[strName]))
            //    return "unsafe string";
            //return StringHelper.ReplaceHtml(HttpContext.Current.Request.Form[strName].Trim());

            //return StringHelper.ReplaceSqlInject(HttpContext.Current.Request.Form[strName].Trim();
            if (sqlSafeCheck)
                return StringHelper.CutString(StringHelper.ReplaceSqlInject(isTrim ? HttpContext.Current.Request.Form[strName].Trim() : HttpContext.Current.Request.Form[strName]), 0, maxLen);
            else
                return StringHelper.CutString(isTrim ? HttpContext.Current.Request.Form[strName].Trim() : HttpContext.Current.Request.Form[strName], 0, maxLen);
        }


        /// <summary>
        /// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">参数</param>
        /// <returns>Url或表单参数的值</returns>
        public static string GetString(string strName, int maxLen = 4000)
        {
            return GetString(strName, false, true, maxLen);
        }

        /// <summary>
        /// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">参数</param>
        /// <param name="sqlSafeCheck">是否进行SQL安全检查</param>
        /// <returns>Url或表单参数的值</returns>
        public static string GetString(string strName, bool sqlSafeCheck, bool isTrim, int maxLen = 4000)
        {
            if ("".Equals(GetQueryString(strName)))
                return GetFormString(strName, sqlSafeCheck, isTrim, maxLen);
            else
                return GetQueryString(strName, sqlSafeCheck, isTrim, maxLen);
        }
        #endregion

       


        
        /// <summary>
        /// URL是否包含查询参数
        /// </summary>
        /// <param name="strName"></param>
        /// <returns></returns>
        public static bool HasQueryKey(string strName)
        {
            if (HttpContext.Current.Request.QueryString != null && HttpContext.Current.Request.QueryString.AllKeys != null && HttpContext.Current.Request.QueryString.AllKeys.Contains(strName))
                return true;
            return false;
        }

       

       
       

        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(result))
                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (string.IsNullOrEmpty(result))
                result = HttpContext.Current.Request.UserHostAddress;

            if (string.IsNullOrEmpty(result) || !StringHelper.IsIP(result))
                return "127.0.0.1";
            return result;
        }

        /// <summary>
        /// 是否微信浏览器
        /// </summary> 
        public static bool IsWeiXinBrowser()
        {
            if (IsAppBrowser())
            {
                var userAgent = GetUserAgent();
                if (!string.IsNullOrWhiteSpace(userAgent) && userAgent.Contains("MicroMessenger"))
                    return true;
            }
            return false;
        }
        /// <summary>
        /// 是否手机浏览器
        /// </summary> 
        public static bool IsAppBrowser()
        {
            var userAgent = GetUserAgent();
            var mathList = new List<string>() { "iPhone", "Android", "Windows Phone" };//iPad
            if (!string.IsNullOrWhiteSpace(userAgent) && mathList.Any(m => userAgent.Contains(m)))
                return true;
            return false;
        }
        ///// <summary>
        ///// 获取操作系统
        ///// </summary> 
        //public static OS_Type GetOSByBrowser()
        //{
        //    var userAgent = GetUserAgent();
        //    //var mathList = new List<string>() { "iPhone", "Android", "Windows Phone", "iPad" };//iPad
        //    if (string.IsNullOrWhiteSpace(userAgent))
        //        return OS_Type.None;
        //    if (userAgent.Contains("iPhone"))
        //        return OS_Type.Iphone;
        //    else if (userAgent.Contains("Android"))
        //        return OS_Type.Android;
        //    else if (userAgent.Contains("Windows Phone"))
        //        return OS_Type.WindowsPhone;
        //    else if (userAgent.Contains("iPad"))
        //        return OS_Type.IPad;
        //    else
        //        return OS_Type.PC;
        //}


        /// <summary>
        /// 获取客户端信息
        /// </summary>
        /// <returns></returns>
        public static string GetUserAgent(int maxLen = 2000)
        {
            string result = string.Empty;
            result = System.Web.HttpContext.Current.Request["HTTP_USER_AGENT"];
            if (string.IsNullOrEmpty(result))
            {
                result = System.Web.HttpContext.Current.Request["User-Agent"];
            }
            if (!string.IsNullOrEmpty(result))
            {
                result = result.Trim();
            }

            return StringHelper.CutString(result, 0, maxLen);
        }

        #region 根据白名单获取手机信息

        /// <summary>
        /// 获取手机信息，这里获取的数据时插入到访问记录时的客户端数据信息
        /// </summary>
        /// <returns></returns>
        public static string GetAppUserAgent()
        {
            string result = string.Empty;
            result += "Phone:" + GetAppPhoneNumber() + ";";
            result += "UserAgent:" + GetUserAgent() + ";";
            result += "x-up-bear-type:" + System.Web.HttpContext.Current.Request["HTTP_X_UP_BEAR_TYPE"] + ";";

            return result;
        }

        /// <summary>
        /// 自动获取手机号码信息，如果无法获取到
        /// </summary>
        /// <returns>手机号码</returns>
        public static string GetAppPhoneNumber()
        {
            string result = string.Empty;
            result = System.Web.HttpContext.Current.Request["HTTP_X_UP_CALLING_LINE_ID"];
            if (string.IsNullOrEmpty(result) || !isPhoneNumber(result))
            {
                result = System.Web.HttpContext.Current.Request["x-up-calling-line-id"];
            }
            if (string.IsNullOrEmpty(result) || string.IsNullOrEmpty(result.Trim()))
            {
                result = string.Empty;
            }
            else
            {
                result = result.Trim();
                if (result.Length == 13)
                {
                    result = result.Substring(2);
                }
            }

            return result;
        }

        private static bool isPhoneNumber(string number)
        {
            if (string.IsNullOrEmpty(number) || string.IsNullOrEmpty(number.Trim()))
            {
                return false;
            }
            Regex reg = new Regex("^(86)*1[0-9]{10}$");
            //多个判断，错误的情况少走正则匹配耗掉时间
            if ((number.Length == 11 || number.Length == 13) && reg.IsMatch(number.Trim()))
            {
                return true;
            }
            return false;
        }

        #endregion
    }
}
